import { createStore } from "vuex";
import persistedState from "vuex-persistedstate";
import { menuItem } from "@/config/menuConfig";
import menuConfig from "@/config/projectOptions";
import { setLocale } from "@/config/languages";

export default createStore({
  state: {
    locale: "zhCn", //当前语言
    tabIndex: "", //选中menu位置
    routerPath: [] as menuItem[] | undefined,
    isCollapse: "", //是否展开menu
    displayMode: "", //暗色模式
  },
  mutations: {
    setLocale(state, value) {
      state.locale = value;
      setLocale(value);
    },
    setTabIndex(state, value) {
      state.tabIndex = value;
    },
    setRouterPath(state, value) {
      // 路径 根据路径 返回路径对象 深度遍历
      /* let x = (list: string[], menu: menuItem[]): menuItem[] | undefined => {
        for (let i of menu) {
          if (list.includes(i.key)) {
            if (i.children) {
              if (Array.isArray(i.children) && i.children) {
                return [
                  i,
                  ...x(list, i.children) as menuItem[]
                ]
              } else {
                return [
                  i,
                  ...x(list, Object.values(i.children).flat()) as menuItem[]
                ]
              }
            } else {
              return [i]
            }
          }
        }
      } */
      // 单个路由地址
      let z = (path: string, menu: menuItem[]): menuItem[] | undefined => {
        for (let i of menu) {
          if (i.key == path) {
            return [i];
          } else if (i.children && Object.keys(i.children)) {
            if (Array.isArray(i.children)) {
              let fliterData = z(path, i.children);
              if (fliterData) {
                return [i, ...fliterData];
              }
            } else {
              let fliterData = z(path, Object.values(i.children).flat());
              if (fliterData) {
                return [
                  { ...i, children: Object.values(i.children).flat() },
                  ...fliterData,
                ];
              }
            }
          }
        }
        return;
      };
      state.routerPath = z(value, menuConfig.menuList);
      // state.routerPath = value
    },
    setIsCollapse(state, value) {
      state.isCollapse = value;
    },
    setDisplayMode(state, value: "dark" | "") {
      state.displayMode = value;
      document.getElementsByTagName("html")[0].className = state.displayMode;
    },
  },
  actions: {},
  modules: {},
  plugins: [
    persistedState({
      // 默认存储在localStorage 现改为sessionStorage
      storage: window.localStorage,
      // 本地存储数据的键名
      key: "cache",
      reducer: (state) => {
        return {
          locale: state.locale,
          tabIndex: state.tabIndex,
          routerPath: state.routerPath,
          isCollapse: state.isCollapse,
          displayMode: state.displayMode,
        };
      },
      // 指定需要存储的模块，如果是模块下具体的数据需要加上模块名称，如user.token
      paths: [],
    }),
  ],
});
